package gui;

import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Throwables.propagate;

import java.util.Collection;
import java.util.Vector;
import java.util.concurrent.ExecutionException;

import javax.swing.DefaultComboBoxModel;
import javax.swing.MutableComboBoxModel;

import libraries.Library;
import metagrammar.Operator;
import metagrammar.Type;
import util.OperatorWrapper;

public class LibraryWrapper implements OperatorModelProvider, TypeModelProvider {
    
    private final Library library;
    
    private MutableComboBoxModel<OperatorWrapper> operatorModel;
    private MutableComboBoxModel<Type> typeModel;
    
    public LibraryWrapper(Library lib)
    {
        checkNotNull(lib);
        this.library = lib;
    }
    
    public Library getLibrary()
    {
        return library;
    }
    
    @Override
    public MutableComboBoxModel<OperatorWrapper> getOperatorModel()
    {
        if(operatorModel == null) {
            try {
                Collection<Operator> ops = library.loadOperators();
                Vector<OperatorWrapper> vec = new Vector<OperatorWrapper>(ops.size());
                for(Operator op : ops) {
                    vec.add(new OperatorWrapper(op));
                }
                operatorModel = new DefaultComboBoxModel<OperatorWrapper>(vec);
            }
            catch(ExecutionException e) {
                e.printStackTrace();
                //throw propagate(e);
            }
        }
        return operatorModel;
    }
    
    @Override
    public MutableComboBoxModel<Type> getTypeModel()
    {
        if(typeModel == null) {
            try {
                Collection<Type> types = library.loadTypes();
                Vector<Type> vec = new Vector<Type>(types);
                typeModel = new DefaultComboBoxModel<Type>(vec);
            }
            catch(ExecutionException e) {
                throw propagate(e);
            }
        }
        return typeModel;
    }
    
    @Override
    public String toString()
    {
        return library.toString();
    }
}